import {
  myRequesy
} from '../../request/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    code: "",
    isShow: false,
    second: 3,
  },
  tmier:null,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      code: options.auth_code
    })

  },
  // 登录授权
  getLogin() {
    let that = this
    wx.getUserProfile({
      desc: '获取您的用户名和头像',
      success(res1) {
        wx.login({
          success(res2) {
            let userData = {
              code: res2.code,
              nickName: res1.userInfo.nickName,
              avatarUrl: res1.userInfo.avatarUrl
            }
            myRequesy({
              url: 'Login',
              data: userData,
              method: "POST",
            }).then(res => {
              if (res.code === 0) {
                wx.setStorage({
                  data: res.data,
                  key: 'userInfo',
                  success() {
                    that.getUpAuth()
                  }
                })
              }
            })
          }
        })
      }
    })
  }, 

  //点击授权
  headleAuth() {
    if (wx.getStorageSync('userInfo')) {
      this.getUpAuth()
    } else {
      this.getLogin()
    }
  },


  // 获取授权
  getUpAuth() {
    let that = this
    myRequesy({
      url: 'update-auth',
      method: "POST",
      data: {
        auth_code: that.data.code
      }
    }).then(res => {
      if (res.code === 0) {
        that.setData({
          isShow: true,
        })
        that.headleCountdown()
      } else {
        that.getLogin()
      }
    })
  },


  // 返回首页
  headleBask() {
    clearInterval(this.tmier)
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },


  // 定时器
  headleCountdown() {
    let that = this
    let {second} = that.data
    that.tmier = setInterval(() => {
      second -= 1
      that.setData({second})
      if (second === 0) {
        that.headleBask()
        clearInterval(that.tmier)
      }
    }, 1000)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

})